//
//  FileOperator.m
//  AutoCompiler_Script
//
//  Created by Vescky on 12-12-18.
//  Copyright (c) 2012年 Vescky. All rights reserved.
//

#import "FileOperator.h"
#import "PathParser.h"
#import "RegexKitLite.h"

@implementation FileOperator
static FileOperator *fileOperator;

+ (id)shareFileOperator {
    if (!fileOperator) {
        fileOperator = [[FileOperator alloc] init];
    }
    
    return fileOperator;
}

//遍历指定目录，返回一个数组
+ (NSMutableArray*)ergodicFolder:(NSString*)_folder {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *fileList = [[NSArray alloc] init];
    fileList = [fm contentsOfDirectoryAtPath:_folder error:nil];
    NSMutableArray *fileArray = [[NSMutableArray alloc] init];
    NSMutableArray *folderArray = [[NSMutableArray alloc] init];
    BOOL isDir = NO;
    //在上面那段程序中获得的fileList中列出文件夹名
    for (NSString *file in fileList) {
        NSString *path = [_folder stringByAppendingPathComponent:file];
        [fm fileExistsAtPath:path isDirectory:(&isDir)];
        if (!isDir) {
            [fileArray addObject:file];
        }
        else {
            [folderArray addObject:file];
        }
        isDir = NO;
    }
    
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];

    [resultArr addObject:folderArray];
    [resultArr addObject:fileArray];
    
    return resultArr;
}



+ (bool)replaceFile:(NSString*)oldFile withNewFile:(NSString*)newFile {
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:newFile]) {
        return NO;
    }
    if ([fm fileExistsAtPath:oldFile]) {
        [fm removeItemAtPath:oldFile error:nil];
    }
    [fm copyItemAtPath:newFile toPath:oldFile error:nil];
    return YES;
}


//递归算法,遍历目录以及每一层子目录，返回一个目录内的所有文件
- (NSMutableArray *)fileErgodicor:(NSString *)path {
    NSMutableArray *nameList = [self getNameListOfFolder:path];
    nameList = [self deleteSystemHiddenFileFromList:nameList];
    NSMutableArray *resultList = [[NSMutableArray alloc] init];
    if (![self isExistFolderAtPath:path list:nameList]) {
        resultList = [self combineArray:resultList withArray:nameList];
        return resultList;
    }
    else {
        resultList = [self selectType:NO baseFolder:path fromList:nameList combineWith:resultList];
        NSMutableArray *folderList = [self selectType:YES baseFolder:path fromList:nameList combineWith:nil];
        for (int i = 0; i < [folderList count]; i++) {
            NSString *fPath = [path stringByAppendingPathComponent:[folderList objectAtIndex:i]];
            NSMutableArray *fResultArr = [self fileErgodicor:fPath];
            resultList = [self selectType:NO baseFolder:fPath fromList:fResultArr combineWith:resultList];
        }
    }
    return resultList;
}

//遍历目录中特定后缀的文件或者包
- (NSMutableArray*)fileErgodicor:(NSString*)path withExtension:(NSString*)extension {
    NSMutableArray *allList = [self getNameListOfFolder:path];
    allList = [self deleteSystemHiddenFileFromList:allList];
    NSMutableArray *nameList = [self getListFromFileList:allList exceptType:extension isDelete:YES];
    
    NSMutableArray *resultList = [[NSMutableArray alloc] init];
    resultList = [self getListFromFileList:allList exceptType:extension isDelete:NO];
    
    if (![self isExistFolderAtPath:path list:nameList]) {
        resultList = [self combineArray:resultList withArray:nameList];
        return resultList;
    }
    else {
        resultList = [self selectExtensionType:extension fromList:nameList combineWith:resultList isDelete:NO];
        NSMutableArray *folderList = [self selectType:YES baseFolder:path fromList:nameList combineWith:nil];
        
        for (int i = 0; i < [folderList count]; i++) {
            NSString *fPath = [path stringByAppendingPathComponent:[folderList objectAtIndex:i]];
            NSMutableArray *fResultArr = [self fileErgodicor:fPath withExtension:extension];
            resultList = [self selectExtensionType:extension fromList:fResultArr combineWith:resultList isDelete:NO];
        }
    }
    return resultList;
}

#pragma mark - Private
//判断该层目录是否还有子目录
- (bool)isExistFolderAtPath:(NSString*)folderPath list:(NSArray*)nameList {
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL hasDir = NO;
    for (int i = 0; i < [nameList count]; i++) {
        NSString *path = [folderPath stringByAppendingPathComponent:[nameList objectAtIndex:i]];
        [fm fileExistsAtPath:path isDirectory:&hasDir];
        if (hasDir) {
            return YES;
        }
    }
    return NO;
}

//返回除去特定类型的名字的列表数组
- (NSMutableArray*)getListFromFileList:(NSArray*)nameList exceptType:(NSString*)_type isDelete:(bool)isDelete {
    NSMutableArray *checkList = [[NSMutableArray alloc] init];
    //剔除文件类型
    for (int i = 0; i < [nameList count]; i++) {
        NSString *fName = [nameList objectAtIndex:i];
        NSArray *arr = [fName componentsSeparatedByString:@"."];
        if (!arr || [arr count] <= 1 || [[arr objectAtIndex:0] isEqualToString:@""]) {
            if (isDelete) {
                [checkList addObject:fName];
            }
            continue;
        }
        NSString *fExtension = [arr lastObject];
        if (isDelete) {
           if (![fExtension isEqualToString:_type]) {
            [checkList addObject:fName];
           }
        }
        else {
            if ([fExtension isEqualToString:_type]) {
                [checkList addObject:fName];
            }
        }
        
    }
    
    return checkList;
}

//获取该层目录所有项目的name
- (NSMutableArray*)getNameListOfFolder:(NSString*)folderName {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSMutableArray *fileList = [[NSMutableArray alloc] initWithArray:[fm contentsOfDirectoryAtPath:folderName error:nil]];
    return fileList;
}

//获取列表中特定类型的名称，并存入数组中,type 是否为目录
- (NSMutableArray*)selectType:(bool)isDir baseFolder:(NSString*)folderPath fromList:(NSMutableArray*)nameList combineWith:(NSMutableArray*)resultList {
    NSFileManager *fm = [NSFileManager defaultManager];
    if (!resultList) {
        resultList = [[NSMutableArray alloc] init];
    }

    for (int i = 0; i < [nameList count]; i++) {
        BOOL flag = NO;
        NSString *path = [folderPath stringByAppendingPathComponent:[nameList objectAtIndex:i]];
        [fm fileExistsAtPath:path isDirectory:&flag];
        if (flag == isDir) {
            [resultList addObject:[nameList objectAtIndex:i]];
        }
    }
    
    return resultList;
}

//获取列表中特定扩展名类型文件，并存入数组中,type 是否为目录
- (NSMutableArray*)selectExtensionType:(NSString*)_type fromList:(NSMutableArray*)nameList combineWith:(NSMutableArray*)resultList isDelete:(bool)isDelete {
    if (!resultList) {
        resultList = [[NSMutableArray alloc] init];
    }
    
    for (int i = 0; i < [nameList count]; i++) {
        NSString *fName = [nameList objectAtIndex:i];
        NSArray *arr = [fName componentsSeparatedByString:@"."];
        if ([arr count] <= 1) {
            if (isDelete) {
                [resultList addObject:fName];
            }
            continue;
        }
        NSString *fExtension = [arr lastObject];
        if (isDelete) {
            if (![fExtension isEqualToString:_type]) {
                [resultList addObject:fName];
            }
        }
        else {
           if ([fExtension isEqualToString:_type]) {
               [resultList addObject:fName];
           }
        }
        
    }
    
    return resultList;
}

//合并数组
- (NSMutableArray*)combineArray:(NSArray*)_arr1 withArray:(NSArray*)_arr2 {
    NSMutableArray *resultArr = [[NSMutableArray alloc] initWithArray:_arr1];
    for (int i = 0; i < [_arr2 count]; i++) {
        [resultArr addObject:[_arr2 objectAtIndex:i]];
    }
    return resultArr;
}

//剔除系统的隐藏文件
- (NSMutableArray*)deleteSystemHiddenFileFromList:(NSMutableArray*)nameList {
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [nameList count]; i++) {
        NSString *str = [nameList objectAtIndex:i];
        NSString *headStr = [str substringToIndex:1];
        if (![headStr isEqualToString:@"."]) {
            [resultArr addObject:str];
        }
    }
    
    return resultArr;
}

//删除无后缀的文件
- (NSMutableArray*)deleteFileWithoutExtensionFromList:(NSMutableArray*)nameList {
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [nameList count]; i++) {
        NSString *str = [nameList objectAtIndex:i];
        NSArray *arr = [str componentsSeparatedByString:@"."];
        if ([arr count] > 1) {
            [resultArr addObject:str];
        }
    }
    
    return resultArr;
}

- (void)cleanOutputFolders {
    //情况输出的目录
    PathParser *pp = [PathParser sharePathParser];
    [self cleanFolder:pp.outputAppPath];
    [self cleanFolder:pp.outputLogFilesPath];
}

//清空一个目录
- (bool)cleanFolder:(NSString*)path {
    NSMutableArray *arr = [self getNameListOfFolder:path];
    if (!arr || [arr count] <= 0) {
        return NO;
    }
    
    NSFileManager *fm = [NSFileManager defaultManager];
    for (int i = 0; i < [arr count]; i++) {
        NSString *fName = [arr objectAtIndex:i];
        [fm removeItemAtPath:[path stringByAppendingPathComponent:fName] error:nil];
    }
    return YES;
}

//同步下载，非异步操作
- (bool)synDownloadZipPackage:(NSString*)urlString {
    NSURL    *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSError *error = nil;
    NSData   *data = [NSURLConnection sendSynchronousRequest:request
                                           returningResponse:nil
                                                       error:&error];
    
    PathParser *pp = [PathParser sharePathParser];
    
    /* 下载数据 */
    NSString *zpPath = pp.incomeBundlePath;//[pp.workSpaceFolderPath stringByAppendingPathComponent:@"ZipPackage"];
    zpPath = [zpPath stringByDeletingLastPathComponent];
    
    NSString *zipShellPath = [pp.scriptFilesPath stringByAppendingPathComponent:@"ChangeZipToBundle.sh"];
    
    //首先清空目录
    [self cleanFolder:zpPath];
    
    if (data != nil){
        NSLog(@"下载成功\n");
        NSString *saveFilePath = [zpPath stringByAppendingPathComponent:@"projectinfo.zip"];
        NSLog(@"save file at path:%s\n",[saveFilePath UTF8String]);
        if ([data writeToFile:saveFilePath atomically:YES]) {
            NSString *cString = [NSString stringWithFormat:@"%@ %@ %@",zipShellPath,[zpPath stringByAppendingPathComponent:@"projectinfo.zip"],zpPath];
            NSLog(@"%s\n",[cString UTF8String]);
            system([cString UTF8String]);
            NSLog(@"保存成功.\n");
            return YES;
        }
        else
        {
            NSLog(@"保存失败.\n");
            return NO;
        }
        
    } else {
        return NO;
    }
    
    
}

- (bool)synDownloadCertsPackage:(NSString*)urlString {
    NSURL    *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSError *error = nil;
    NSData   *data = [NSURLConnection sendSynchronousRequest:request
                                           returningResponse:nil
                                                       error:&error];
    
    PathParser *pp = [PathParser sharePathParser];
    
    /* 下载数据 */
    NSString *iosProjPath = [pp.outIosProjectPath stringByDeletingLastPathComponent];//[pp.workSpaceFolderPath stringByAppendingPathComponent:@"ZipPackage"];
    
    if (data != nil){
        NSLog(@"下载成功\n");
        NSString *saveFilePath = [iosProjPath stringByAppendingPathComponent:[urlString lastPathComponent]];
        NSLog(@"save file at path:%s\n",[saveFilePath UTF8String]);
        if ([data writeToFile:saveFilePath atomically:YES]) {
            NSLog(@"保存成功.\n");
            return YES;
        }
        else
        {
            NSLog(@"保存失败.\n");
            return NO;
        }
    } else {
        return NO;
    }
}

////同步下载图片
//- (NSImage*) getImageFromURL:(NSString *)fileURL {
//    NSLog(@"执行图片下载函数");
//    NSImage *result;
//    
//    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
//    result = [NSImage imageWithData:data];
//    
//    return *result;
//}
//
//
//-(void) saveImage:(NSImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
//    if ([[extension lowercaseString] isEqualToString:@"png"]) {
//        [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
//    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
//        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
//    } else {
//        //ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
//        NSLog(@"文件后缀不认识");
//    }
//}



//遍历当前目录，返回一个列表
- (NSMutableArray*)getListOfPath:(NSString*)gPath isDir:(bool)dir {
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSArray *fileList = [[NSArray alloc] init];
    fileList = [fm contentsOfDirectoryAtPath:gPath error:nil];
    NSMutableArray *fileArray = [[NSMutableArray alloc] init];
    NSMutableArray *folderArray = [[NSMutableArray alloc] init];
    BOOL isDir = NO;
    for (NSString *file in fileList) {
        NSString *path = [gPath stringByAppendingPathComponent:file];
        [fm fileExistsAtPath:path isDirectory:(&isDir)];
        if (!isDir) {
            [fileArray addObject:file];
        }
        else {
            [folderArray addObject:file];
        }
        isDir = NO;
    }
    
    if (dir) {
        return folderArray;
    }
    else {
        return fileArray;
    }
    
}


- (NSString*)getIconPathFromZip {
    PathParser *pp = [PathParser sharePathParser];
    NSString *iconDir = [pp.incomeBundlePath stringByAppendingPathComponent:@"www/homepage/icon"];
    NSString *iconPath = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *fileList = [[NSArray alloc] init];
    fileList = [fm contentsOfDirectoryAtPath:iconDir error:nil];
    for (int i = 0; i < [fileList count]; i++) {
        NSString *fName = [fileList objectAtIndex:i];
        if ([[[fName pathExtension] lowercaseString] isEqualToString:@"png"]) {
            iconPath = fName;
        }
    }
    return iconPath;
}


@end
